/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2024 All Rights Reserved.
 */
package com.alipay.demo.listener;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.msg.AlipayMsgClient;
import com.alipay.api.msg.MsgHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * websocket监听支付宝From蚂蚁消息，团购券会用到的消息接口有：
 * 1.alipay.open.app.item.status.notify 商品状态变更消息同步接口：用来商品状态变更消息同步，包括但不限于商品审核中、审核驳回、已冻结、已下架、出售中等引起的状态变更，商家/服务商可以监听本接口感知商品状态信息的变更。
 * 2.alipay.marketing.certificate.certification.notify 凭证消息通知接口：用于向商家同步凭证的触发事件，如发放、核销、取消核销、退款等
 * 3.alipay.open.app.localitem.spustatus.notify 本地商品SPU状态变更消息：包括审核中、审核驳回、已生效、已失效
 * 4.alipay.open.mini.order.changed、alipay.open.mini.order.aftersale.changed
 *
 * @author jishupei.jsp
 * @version : WebsocketListener, v0.1 2024年03月07日 4:45 下午 jishupei.jsp Exp $
 */
@Component
public class WebsocketListener implements ApplicationListener<ApplicationReadyEvent> {
    private static final Logger logger = LogManager.getLogger(WebsocketListener.class);

    @Value("${alipay.appid}")
    private String appId;

    @Value("${alipay.privatekey}")
    private String privateKey;

    @Value("${alipay.alipaypublickey}")
    private String alipayPublicKey;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        String serverHost = "openchannel.alipay.com";
        boolean isSSL = true;
        String signType = "RSA2";
        String charset = "UTF-8";
        AlipayMsgClient alipayMsgClient = AlipayMsgClient.getInstance(appId);
        try {
            alipayMsgClient.setConnector(serverHost, isSSL);
            alipayMsgClient.setSecurityConfig(signType, privateKey, alipayPublicKey);
            alipayMsgClient.setCharset(charset);
            alipayMsgClient.setLoadTest(false);

            // 消息接收
            alipayMsgClient.setMessageHandler(new MsgHandler() {
                public void onMessage(String msgApi, String msgId, String bizContent) {
                    logger.info("===========================================");
                    logger.info("receive message. msgApi:" + msgApi + " msgId:" + msgId + " bizContent:" + bizContent);

                    JSONObject jsonObject = JSONObject.parseObject(bizContent);
                    if ("alipay.open.app.item.status.notify".equals(msgApi)) {
                        logger.info("order_id：" + jsonObject.getString("item_id"));
                        logger.info("out_item_id：" + jsonObject.getString("out_item_id"));
                        logger.info("spu_status：" + jsonObject.getString("spu_status"));
                    } else if ("alipay.marketing.certificate.certification.notify".equals(msgApi)) {
                        logger.info("order_id：" + jsonObject.getString("order_id"));
                        logger.info("action：" + jsonObject.getString("action"));
                    } else if("alipay.open.app.localitem.spustatus.notify".equals(msgApi)){
                        logger.info("spu_id：" + jsonObject.getString("spu_id"));
                        logger.info("out_spu_id：" + jsonObject.getString("out_spu_id"));
                        logger.info("spu_status：" + jsonObject.getString("spu_status"));
                    }
                    logger.info("===========================================");
                }
            });

            alipayMsgClient.connect();

            logger.info("websocket listener start successfully......");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
